package javaIo;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by zzy on 2018/4/2.
 */
public class Bio {

    public static void main(String[] args) {
        try {

            //2、线程池处理
            ExecutorService threadPool= Executors.newCachedThreadPool();
            ExecutorService threadPoolFix= Executors.newFixedThreadPool(3);
            ServerSocket serverSocket=new ServerSocket(12345);

            while (true){
                Socket socket=serverSocket.accept();
                System.out.println("客户端"+socket.getInetAddress()+":链接上了");
                threadPoolFix.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            InputStream inputStream=socket.getInputStream();
                            byte[]b=new byte[1024];
                            int a=0;
                            while ( (a=inputStream.read(b))!=-1){
                                String result=new String(b,0,a,"GBK");
                                System.out.print(result);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });
                //1、获取客户端连接后，把客户端连接处理交给另个线程处理
/*                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            InputStream inputStream=socket.getInputStream();
                            byte[]b=new byte[1024];
                            int a=0;
                            while ( (a=inputStream.read(b))!=-1){
                                String result=new String(b,0,a,"GBK");
                                System.out.print(result);
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                }).start();*/

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
